package org.jeecg.modules.sensor.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.jeecg.common.util.DateStyle;
import org.jeecg.common.util.DateUtil;
import org.jeecg.common.util.DeviceParam;
import org.jeecg.modules.sensor.model.Page;
import org.jeecg.modules.sensor.service.ISensorService;
import org.jeecg.modules.sensor.util.SensorUtils;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class SensorSercieImpl implements ISensorService {
	
	public List<Map<Object, Object>> chartAnalysis(String deviceName, String periodType, Integer pageNo, Integer pageSize) {
		// 参数集合
		Map<String, Object> paramMap = new HashMap<String, Object>();
		// 先获取设备最新数据时间
		List<Map<Object, Object>> dataList = null;
		String device_name = deviceName.split("-")[0];
		paramMap.put("device_name", deviceName.split("-")[1]);
		if(device_name.equals(SensorUtils.WATER_SENSOR_ATTRIBUTE)) {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_W_DEVICEDATA_NEW_TIME, paramMap);
		} else {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_DEVICEDATA_NEW_TIME, paramMap);
		}
		String endTime = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS);
		if(dataList.size() > 0) {
			endTime = dataList.get(0).get("event_time").toString();
		}
		String startTime = DateUtil.addMinute(endTime, -30);
		if(periodType.equals("1")) {
			startTime = DateUtil.addMinute(endTime, -30);
			paramMap.put("pageSize", 30*6);
		} else if(periodType.equals("2")) {
			startTime = DateUtil.addMinute(endTime, -60);
			paramMap.put("pageSize", 60*6);
		} else if(periodType.equals("3")) {
			startTime = DateUtil.addMinute(endTime, -240);
			paramMap.put("pageSize", 240*6);
		} else if(periodType.equals("4")) {
			startTime = DateUtil.addMinute(endTime, -1440);
			paramMap.put("pageSize", 1440*6);
		} else if(periodType.equals("5")) {
			startTime = DateUtil.addMinute(endTime, -10080);
			paramMap.put("pageSize", 10080*6);
		}
		paramMap.put("startTime", startTime);
		paramMap.put("endTime", DateUtil.addMinute(endTime, 1));
		// 由于API接口默认拿到200条数据， 但是实际上会大于200条，所以需要指定条数
		paramMap.put("pageNo", 0);
		
		String paramKey = "";
		String paramValue = "";
		if(device_name.equals(SensorUtils.WATER_SENSOR_ATTRIBUTE))  {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_W_DEVICEDATA, paramMap);
			paramKey = DeviceParam.Water_Sensor_Attribute.getParamKey();
			paramValue = DeviceParam.Water_Sensor_Attribute.getParamValue();
		} else {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_DEVICEDATA, paramMap);
			if(device_name.equals(SensorUtils.AIR_SENSOR_ATTRIBUTE)) {
				paramKey = DeviceParam.Air_Sensor_Attribute.getParamKey();
				paramValue = DeviceParam.Air_Sensor_Attribute.getParamValue();
			} else if(device_name.equals(SensorUtils.SOIL_SENSOR_ATTRIBUTE)) {
				paramKey = DeviceParam.Soil_Sensor_Attribute.getParamKey();
				paramValue = DeviceParam.Soil_Sensor_Attribute.getParamValue();
			} else if(device_name.equals(SensorUtils.GAS_SENSOR_ATTRIBUTE)) {
				paramKey = DeviceParam.Gas_Sensor_Attribute.getParamKey();
				paramValue = DeviceParam.Gas_Sensor_Attribute.getParamValue();
			}
		}
		if(dataList == null) {
			return null;
		}
		// 返回的格式,将dataList转为图表所需要的格式
		List<Map<Object, Object>> resultList = new ArrayList<Map<Object,Object>>();
		List<String> chartNameList = new ArrayList<String>();
		Map<String, String[][]> chartDataMap = new HashMap<String, String[][]>();
		int index = 0;
		for(Map<Object, Object> tempDataMap : dataList) {
			String event_time = tempDataMap.get("event_time").toString();
			for(Map.Entry<Object, Object> entry : tempDataMap.entrySet()) {
				if(!entry.getKey().equals("device_name") && !entry.getKey().equals("event_time") && paramKey.contains(entry.getKey().toString())) {
					if(index == 0) {
						chartNameList.add(entry.getKey().toString());
					}
					String[][] tempData = chartDataMap.get(entry.getKey().toString());
					if(tempData == null) {
						tempData = new String[dataList.size()][2];
						chartDataMap.put(entry.getKey().toString(), tempData);
					}
					tempData[index][0] = event_time;
					tempData[index][1] = entry.getValue().toString();
				}
			}
			index ++;
		}
		Map<String, String> legendMap = new HashMap<String, String>();
		String[] keyArray = paramKey.split(",");
		String[] valueArray = paramValue.split(",");
		for(int i = 2; i < keyArray.length; i++) {
			legendMap.put(keyArray[i], valueArray[i]);
		}
		for(String name : chartNameList) {
			Map<Object, Object> tempParamMap = new HashMap<Object, Object>();
			tempParamMap.put("name", legendMap.get(name));
			tempParamMap.put("type", "line");
			tempParamMap.put("connectNulls", true);
			tempParamMap.put("data", chartDataMap.get(name));
			resultList.add(tempParamMap);
		}
		return resultList;
	}
	
	public Page<Map<Object, Object>> queryDataByParam(String startTime, String endTime, String deviceName, Integer pageNo, Integer pageSize) {
		// 参数集合
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("startTime", startTime);
		paramMap.put("endTime", endTime);
		//在分页之前先获取总条数
		List<Map<Object, Object>> dataList = null;
		String device_name = deviceName.split("-")[0];
		paramMap.put("device_name", deviceName.split("-")[1]);
		paramMap.put("pageSize", (DateUtil.getIntervalMinutes(startTime, endTime)+1)*6);
		if(device_name.equals(SensorUtils.WATER_SENSOR_ATTRIBUTE))  {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_W_DEVICEDATA_TOTAL, paramMap);
		} else {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_DEVICEDATA_TOTAL, paramMap);
		}
		if(null == dataList) {
			return null;
		} 
		Page<Map<Object, Object>> page = new Page<Map<Object, Object>>();
		page.setTotal(Integer.valueOf(dataList.get(0).get("total").toString()));
		page.setCurrent(pageNo);
		page.setSize(pageSize);
		page.setPages(page.getTotal()%pageSize == 0 ? page.getTotal()/pageSize : page.getTotal()/pageSize+1);
		// 调用获取总条数API后， 休眠2秒，防止1秒内调用2此API，导致API调用失败
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 休眠之后调用获取数据API
		paramMap.put("pageNo", (pageNo-1)*pageSize);
		paramMap.put("pageSize", pageSize);
		if(device_name.equals(SensorUtils.WATER_SENSOR_ATTRIBUTE))  {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_W_DEVICEDATA, paramMap);
		} else {
			dataList = SensorUtils.callAPI(SensorUtils.API_GET_DEVICEDATA, paramMap);
		}
		page.setRecords(dataList);
		return page;
	}
}
